from django.shortcuts import render
import json,re
from django import http
from django_redis import get_redis_connection
from django.http import JsonResponse
from django.views import View
from django.conf import settings
import logging

from django.contrib.auth import login, authenticate, logout
from users.models import User
from ihome.utils.errmsg_info import error_no, error_msg
from libs.qiniuyun.qiniu_storage import storage
from utils.mixin import LoginRequiredJsonMixin

# Create your views here.
logger = logging.getLogger('django')


class RegisterView(View):
    """注册接口"""
    def post(self,request):
        # 1.接收参数
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        phonecode = dict.get('phonecode')
        password = dict.get('password')
        # password2 = dict.get('password2')
        # 2.校验整体
        if not all([mobile,phonecode,password]):
            return http.JsonResponse({
                'errno':error_no['DATAERR'],
                'errmsg':error_msg['DATAERR']
            })
        # 3.手机号校验
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return http.JsonResponse({
                'errno':error_no['DATAERR'],
                'errmsg':error_msg['DATAERR']
            })
        # 4.密码校验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$',password):
            return http.JsonResponse({
                'errno':error_no['PWDERR'],
                'errmsg':error_msg['PWDERR']
            })

        # 6.短信验证码校验
        conn = get_redis_connection('verify_code')
        code_from_redis = conn.get('sms_%s'%mobile)
        if phonecode != code_from_redis.decode():
            return JsonResponse({
                'errno':error_no['DATAERR'],
                'errmsg':error_msg['DATAERR']
            })
        # 7.短信验证码是否过期
        if not code_from_redis:
            return JsonResponse({
                'errno':error_no['DATAERR'],
                'errmsg':error_msg['DATAERR']
            })
        user = User.objects.create_user(username=mobile,password=password,mobile=mobile)

        login(request,user)

        # 8.返回
        return JsonResponse({
            'errno':error_no['OK'],
            'errmsg':error_msg['OK']
        })


class LoginView(View):
    """ 登录接口"""
    def post(self,request):
        # 1.接收参数
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        password = dict.get('password')
        # 2.校验参数
        if not all([mobile,password]):
            return JsonResponse({
                'errno':error_no['DATAERR'],
                'errmsg':error_msg['DATAERR']
            })
        # # 3.验证是否能够登录
        user = authenticate(username=mobile,password=password)
        if user is None:
            return JsonResponse({
                'errno':error_no['LOGINERR'],
                'errmsg':error_msg['LOGINERR']
            })
        # 4.状态保持
        login(request,user)
        # 5.返回json
        return JsonResponse({
            'errno':error_no['OK'],
            'errmsg':error_msg['OK']
        })

    def get(self, request):
        """判断是否登录"""
        if request.user.is_authenticated:
            name = request.user.username

            return http.JsonResponse({
                'errno': error_no['OK'],
                'errmsg': '已登录',
                'data': {'name': name, 'user_id': request.user.id}
            })
        else:
            return http.JsonResponse({'errno': error_no['SESSIONERR'], 'errmsg': error_msg['SESSIONERR']})
        # if request.user.is_authenticated:
        #     name = request.user.username
        #
        #     return http.JsonResponse({
        #         'errno': error_no['OK'],
        #         'errmsg': '已登录',
        #         'data': {'name': name, 'user_id': request.user.id}
        #     })

    def delete(self, request):
        logout(request)

        return http.JsonResponse({'errno': error_no['OK'], 'errmsg': '已登出'})


class UserInfoView(LoginRequiredJsonMixin, View):
    """用户中心"""

    def get(self, request):
        """
        {
            "data": {
                "avatar": "http://oyucyko3w.bkt.clouddn.com/FmWZRObXNX6TdC8D688AjmDAoVrS",
                "create_time": "2017-11-07 01:10:21",
                "mobile": "18599998888",
                "name": "哈哈哈哈哈哈",
                "user_id": 1
            },
            "errmsg": "OK",
            "errno": "0"
        }
        声明：数据库中目前没有avatar字段，create_time我们用date_joined字段。所以需要先给模型类添加字段
        """
        user = request.user
        avatar = settings.QINIU_URL + str(user.avatar)

        # 1、获取数据
        data = {
            "avatar": avatar,
            "create_time": user.date_joined,
            "mobile": user.mobile,
            "name": user.username,
            "user_id": user.id
        }

        # 构建响应数据
        return JsonResponse({"errno": error_no['OK'], "errmsg": "OK", "data": data})


class AvatarView(LoginRequiredJsonMixin, View):

    def post(self, request):
        # 1.接收参数
        avatar = request.FILES.get("avatar")

        if not avatar:
            return JsonResponse({"errno": error_no['PARAMERR'], "errmsg": "参数错误"})

        # 读出文件对象的二进制数据
        file_data = avatar.read()

        try:
            key = storage(file_data)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"errno": error_no['THIRDERR'], "errmsg": "上传图片失败"})

        try:
            request.user.avatar = key
            request.user.save()
        except request.user.DatabaseError as e:
            logger.error(e)
            return JsonResponse({"errno": error_no['SERVERERR'], "errmsg": "图片保存失败"})

        data = {
            "avatar_url": settings.QINIU_URL + str(key)
        }
        return JsonResponse({"errno": error_no['OK'], "errmsg": "OK", "data": data})


class ModifyNameView(LoginRequiredJsonMixin, View):

    def put(self, request):
        data = json.loads(request.body.decode())
        username = data.get('name')
        # 获取当前登录用户的用户名
        user = request.user

        try:
            user.username = username
            user.save()
        except user.DatabaseError as e:
            logger.error(e)
            return JsonResponse({"errno": error_no['SERVERERR'], "errmsg": "数据修改失败"})
        return JsonResponse({"errno": error_no['OK'], "errmsg": "修改成功"})


class UserAuthView(LoginRequiredJsonMixin, View):
    """用户实名认证"""
    def dispatch(self, *args, **kwargs):
        return super(UserAuthView, self).dispatch(*args, **kwargs)

    def get(self, request):
        # 显示认证信息
        data = request.user.to_auth_dict()
        return JsonResponse({"errno": error_no['OK'], "errmsg": "认证信息查询成功", "data":data})

    def post(self, request):
        # 保存用户认证信息，数据库中添加字段
        # 1.接收参数
        data = json.loads(request.body.decode())
        real_name = data.get('real_name')
        id_card = data.get('id_card')

        # 1.校验参数
        if not all([real_name, id_card]):
            return JsonResponse({"errno": error_no['PARAMERR'], "errmsg": "参数错误"})

        # 校验身份证号码
        if not re.match(r'^(([1][1-5])|([2][1-3])|([3][1-7])|([4][1-6])|([5][0-4])'
                        r'|([6][1-5])|([7][1])|([8][1-2]))\d{4}(([1][9]\d{2})'
                        r'|([2]\d{3}))(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])'
                        r'|([3][0-1]))\d{3}[0-9xX]$',
                        id_card):
            return JsonResponse({"errno": error_no['PARAMERR'], "errmsg": "参数错误"})

        # 3.保存用户信息
        user = request.user
        try:
            user.real_name = real_name
            user.id_card = id_card
            user.save()
        except user.DatabaseError as e:
            logger.error(e)
            return JsonResponse({"errno": error_no['4500'], "errmsg": "数据保存失败"})
        else:
            return JsonResponse({"errno": 0, "errmsg": "认证信息保存成功"})

